import requests

from common.core.base import Field, BaseField
from common.core.enu import ContentTypeEnu, AssertType
from common.pkg.log import log_process
from common.utils.parser import jsonparser
from conf import settings


class RequestMixin:
    @property
    def test_response(self):
        return self.case["res"]

    def get(self) -> dict:
        # return requests.get(url=self.url, headers=self.headers.values(), ).json()
        return self.test_response

    def post(self) -> dict:
        content_type = self.headers.content_type
        data = ContentTypeEnu.get_content_data(content_type, self.data or {})

        # return requests.post(url=self.url, headers=self.headers.values(), data=data).json()
        return self.test_response

    def put(self):
        ...

    def delete(self):
        ...

    @log_process
    def do_request(self, is_depend: bool = False):
        """
        :param is_depend: 是否为依赖用例
        """
        method = self.method.lower()
        try:
            res = getattr(self, method)()
        except AttributeError as e:
            raise AttributeError("不存在的请求方法: %s" % method)
        except Exception as e:
            raise Exception("请求失败: %s" % e)
        else:
            self.response = res
        return self  # 支持链操作

    def assert_res(self):
        json_path = str(self.assertion.json_path).strip()
        try:
            real = jsonparser(self.response, json_path, )
        except Exception:
            raise Exception(f"解析json_path失败，json_path：{json_path}，response：{self.response}")
        except_val = self.assertion.except_value
        assert_type = self.assertion.assert_type
        AssertType.assert_result(assert_type, real, except_val)
        return self

    def get_response(self):
        return self.response


# 头信息
class HeadersField(Field):
    accept = Field(name="Accept")
    content_type = Field(name="Content-Type")
    authorization = Field(name="Authorization", required=False)  # 部分白接口不需要


# 断言信息
class AssertionField(Field):
    json_path = Field(name="json_path")
    except_value = Field(name="except_value")
    assert_type = Field(name="assert_type")


# 请求体信息
class RequestCase(BaseField, RequestMixin):
    url = Field(name="url")
    headers = HeadersField(name="headers")
    data = Field(name="data", required=False)
    assertion = AssertionField(name="assertion")
    method = Field(name="method")
    res = Field(name="res")  # 测试使用而已
